package de.mindshareprojects.datawarehouse.server;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.mindshareprojects.datawarehouse.shared.WebAnalyticsLineItem;



@SuppressWarnings("serial")
public class CSVExport extends HttpServlet {

	PersistenceManager pm = PMF.get().getPersistenceManager();	
	private static Long groupKey;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException {
		
		doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		groupKey = Long.parseLong(request.getParameter("groupId"));
		System.out.println("GET Parameter: " + request.getParameter("groupId"));
		PrintWriter out = response.getWriter();
		response.setContentType("text/csv");
		response.setHeader("content-disposition","attachment; filename=WebTrendsId.csv"); 
		ArrayList <WebAnalyticsLineItem> result=getWebAnalyticsLineItem();

		String head="CampaignID,Description,Creative,Creative Type,Demand Channel,Marketing Activity,Marketing Program,Offer,Partner,Placement,ZielURL";
		out.print(head);

		// String File=head;
		for(WebAnalyticsLineItem item: result){
			out.print("\n");
			out.print(item.getPlacementID().replace("\n", "")+",");
			out.print(item.getDescription()+",");
			out.print(item.getCreative()+",");
			out.print(item.getCreativeType()+",");
			out.print(item.getDemandChannel()+",");
			out.print(item.getMarketingActivity()+",");
			out.print(item.getMarketingProgram()+",");
			out.print(item.getOffer()+",");
			out.print(item.getPartner()+",");
			out.print(item.getPlacement()+",");
			out.print(item.getTargetURL().replace("\n", ""));
		}
	}


	public ArrayList<WebAnalyticsLineItem> getWebAnalyticsLineItem() {
		
		List<WebAnalyticsLineItem> webAnalyticsLineItemList = null;
		ArrayList<WebAnalyticsLineItem> result = new ArrayList<WebAnalyticsLineItem>();
		Query query = pm.newQuery(WebAnalyticsLineItem.class);
		query.setFilter("advertiserGroupKey == groupKeyParam");
		query.declareParameters("Long groupKeyParam");
		
		try{
			webAnalyticsLineItemList = (List<WebAnalyticsLineItem>) query.execute(groupKey);
			for (WebAnalyticsLineItem a: webAnalyticsLineItemList){
				result.add(a);
			}
		} catch (Exception e) {
			System.out.println("Error while trying to query WebAnalyticsLineItem.");
		}		
		return result;
	}	
}
